package com.pvdnc.outguess;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public final class IOUtils {

    public static byte[] readIOInputStream(InputStream inputStream, boolean closeStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        if(closeStream)
            inputStream.close();//关闭IS流
        return bos.toByteArray();
    }

    public static final class IOFile extends File {
        private static final String TAG="FileUtils";

        public IOFile(String pathname) {
            super(pathname);
        }

        public void write(byte[] data,boolean append)
                throws UnsupportedOperationException, IOException {
            if(exists()) {
                if (isDirectory())
                    throw new UnsupportedOperationException(getAbsolutePath() + " is a dictionary");
            }else {
                //noinspection ResultOfMethodCallIgnored
                createNewFile();
            }
            try (FileOutputStream fos = new FileOutputStream(this, append)) {
                fos.write(data);
                fos.flush();
            }
        }

        public void validFileOrThrow()
                throws UnsupportedOperationException, FileNotFoundException {
            if(!exists())
                throw new FileNotFoundException(getAbsolutePath());
            if (isDirectory())
                throw new UnsupportedOperationException(getAbsolutePath() + " is a dictionary");
        }

        public byte[] read()
                throws UnsupportedOperationException, IOException {
            validFileOrThrow();
            try(FileInputStream fis=new FileInputStream(this)){
                return readIOInputStream(fis,false/*try-with-resources会替我们关闭fis*/);
            }
        }

        public static IOFile getAppFile(Context context, String dirName, String fileName){
            File dir= context.getDir(dirName, Context.MODE_PRIVATE);
            String path=dir.getAbsolutePath();
            if(fileName!=null)
                path+="/"+fileName;
            return new IOFile(path);
        }
    }

    public static final class Network {

        private String mUrl;
        public Network(String url){
            mUrl=url;
        }

        public abstract static class DownloadListener{
            private void callOnDownloadCompleted(byte[] data){
                try{
                    onDownloadCompleted(data);
                }catch (Exception e){//阻隔错误
                    e.printStackTrace();
                }
            }

            protected abstract void onDownloadCompleted(byte[] data);

            protected void onError(IOException e){
                e.printStackTrace();
            }
        }

        public void download(final DownloadListener listener) {
            final Thread thread= new Thread("Download"){
                @Override
                public void run() {
                    super.run();
                    try {
                        listener.callOnDownloadCompleted(download());
                    } catch (IOException e) {
                        listener.onError(e);
                    }
                }
            };
            thread.start();
        }

        private byte[] download() throws IOException {
            URL url = new URL(mUrl);
            URLConnection conn = url.openConnection();
            try (InputStream is = conn.getInputStream()) {
                return readIOInputStream(is, false);
            }
        }
    }
}
